import math
import random
import json

distance = 0.02
Users = []
Jigsaws = []

class User():
    def __init__(self, uid, x, y):
        self.uid = uid
        self.x = x
        self.y = y

    def catch(self, piece):
        piece.status = 1
        piece.owner = self.uid

    def dist(self,piece):
        distance = math.sqrt((piece.x - self.x)**2 + (piece.y - self.y)**2)
        print ("distance ",distance)
        return distance

    def GetClosepieces(self,Jigsaw):
        Closepieces = []
        for each in Jigsaw.pieces:
            if each.status == 0:
                if self.dist(each) <= distance:
                    Closepieces.append(each)
        return Closepieces


class Piece():
    def __init__(self, Jigsaw, pid):
        self.pid = pid
        self.rows = 0
        self.columns = 0
        temp = pid
        while temp >= Jigsaw.columns:
            temp -= Jigsaw.columns
            self.rows += 1
        else:
            self.columns = temp
            self.x = Jigsaw.x1 + Jigsaw.width / Jigsaw.columns * (self.columns + random.random())
            self.x1 = Jigsaw.x1 + Jigsaw.width / Jigsaw.columns * self.columns
            self.x2 = Jigsaw.x1 + Jigsaw.width / Jigsaw.columns * (self.columns + 1)
            self.y = Jigsaw.y1 + Jigsaw.length / Jigsaw.rows * (self.rows + random.random())
            self.y1 = Jigsaw.y1 + Jigsaw.length / Jigsaw.rows * self.rows
            self.y2 = Jigsaw.y1 + Jigsaw.length / Jigsaw.rows * (self.rows + 1)
        self.jid = Jigsaw.jid
        self.owner = -1
        self.status = 0
        # print([self.x, self.y])

class Jigsaw():
    def __init__(self, x1, x2, y1, y2):
        global Jigsaws
        self.x1 = x1
        self.x2 = x2
        self.y1 = y1
        self.y2 = y2
        self.width = x2 - x1
        self.length = y2 - y1
        self.pieces = []
        self.rows = 3
        self.columns = 3
        num = len(Jigsaws)
        Jigsaws.append(self)
        self.jid = num
        self.volume = self.rows * self.columns
        for i in range(self.volume):
            piece = Piece(self, i)
            self.pieces.append(piece)
    def contain(self,User):
        print([User.x, User.y, self.x1, self.y1, self.x2, self.y2])
        if User.x > self.x1 and User.x < self.x2 and User.y > self.y1 and User.y < self.y2:
            return True
        else:
            return False


def getJigsaw(a):
    print("getJigsaw")
    dict1 = json.loads(a)
    user_id = dict1["uid"]
    for eachUser in Users:
        if eachUser.uid == user_id:
            eachUser.x = dict1['x']
            eachUser.y = dict1['y']
            for eachJigsaw in Jigsaws:
                if eachJigsaw.contain(eachUser):
                    dict2 = eachJigsaw.__dict__
                    Jigsaw_json = json.dumps(dict2, default=lambda obj: obj.__dict__)
                    return Jigsaw_json
            break
    return ''

def findPieces(a):
    print("findpieces")
    dict1 = json.loads(a)
    user_id = dict1["uid"]
    jigsaw_id = dict1["jid"]
    for eachUser in Users:
        if eachUser.uid == user_id:
            # print(11)
            eachUser.x = dict1['x']
            eachUser.y = dict1['y']
            for eachJigsaw in Jigsaws:
                # print(111)
                if eachJigsaw.jid == jigsaw_id:
                    # print(10)
                    dict2 = eachUser.GetClosepieces(eachJigsaw)
                    class t_:
                        def __init__(self, ps):
                            self.list = ps
                    t = t_(dict2)
                    Closepieces_json = json.dumps(t.__dict__, default=lambda obj: obj.__dict__)
                    return Closepieces_json
            break
    return ''

def getAllInfo(a):
    print("hello")
    class AllInfo:
        def __init__(self):
            self.jigsaws = []
            self.nearbyPieces = []
            self.services = []

    _AllInfo = AllInfo()

    dict1 = json.loads(a)
    user = Users[dict1['uid']]
    user.x = dict1['x']
    user.y = dict1['y']

    contain_jigsaw = None
    other_jigsaws = []
    for j in Jigsaws:
        if j.contain(user):
            contain_jigsaw = j
        else:
            other_jigsaws.append(j)
    if contain_jigsaw:
        _AllInfo.jigsaws = [contain_jigsaw] + other_jigsaws
    else:
        _AllInfo.jigsaws = other_jigsaws


    ps = []
    for j in Jigsaws:
        for p in j.pieces:
            if p.status == 0 and user.dist(p) < distance:
                ps.append(p)
    _AllInfo.nearbyPieces = ps
    print(json.dumps(_AllInfo, default=lambda obj: obj.__dict__)) 
    return json.dumps(_AllInfo, default=lambda obj: obj.__dict__)

def markPiece(a):
    print("markPiece")
    dict1 = json.loads(a)
    if Jigsaws[dict1['jid']].pieces[dict1['pid']].owner == dict1['uid']:
        Jigsaws[dict1['jid']].pieces[dict1['pid']].status = 2
    return "{\"status\":0}"

def catchPiece(a):
    print("catchPiece")
    dict1 = json.loads(a)
    Users[dict1['uid']].catch(Jigsaws[dict1['jid']].pieces[dict1['pid']])
    return "{\"status\":0}"

jigsaw = Jigsaw(121.337195,121.391249,31.14011904,31.19599296)
Users.append(User(0, 0, 0))
print(getAllInfo("{\"uid\":0,\"x\":121.337, \"y\":31.140, \"jid\":1}"))